package main

import (
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"strings"
)

func main() {
	http.HandleFunc("/", handler)
	http.HandleFunc("/healthz", healthzHandler )
	log.Fatal(http.ListenAndServe("localhost:8000", nil))
}

func handler(w http.ResponseWriter, r *http.Request) {
	// 设置code
	code := 200

	for k, v := range r.Header {
		// request head 写入到 response header
		// fmt.Printf("key is: %s, v is : %s \n", k, strings.Join(v,""))
		w.Header().Set(k, strings.Join(v,""))
	}

	// 写入version值
	w.Header().Set("version", os.Getenv("VERSION"))

	// 打印日志
	ip,_ := getIP(r)
	fmt.Printf("client ip is: %s \n" , ip)
	fmt.Printf("response code is: %d \n" , code)

	w.WriteHeader(code)
}

func healthzHandler (w http.ResponseWriter, r *http.Request) {
	// 设置code
	code := 200

	for k, v := range r.Header {
		// request head 写入到 response header
		// fmt.Printf("key is: %s, v is : %s \n", k, strings.Join(v,""))
		w.Header().Set(k, strings.Join(v,""))
	}

	// 写入version值
	w.Header().Set("version", os.Getenv("VERSION"))

	// 打印日志
	ip,_ := getIP(r)
	fmt.Printf("client ip is: %s \n" , ip)
	fmt.Printf("response code is: %d \n" , code)

	w.WriteHeader(code)
}

func getIP(r *http.Request) (string, error) {
	//Get IP from the X-REAL-IP header
	ip := r.Header.Get("X-REAL-IP")
	netIP := net.ParseIP(ip)
	if netIP != nil {
		return ip, nil
	}

	//Get IP from X-FORWARDED-FOR header
	ips := r.Header.Get("X-FORWARDED-FOR")
	splitIps := strings.Split(ips, ",")
	for _, ip := range splitIps {
		netIP := net.ParseIP(ip)
		if netIP != nil {
			return ip, nil
		}
	}

	//Get IP from RemoteAddr
	ip, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		return "", err
	}
	netIP = net.ParseIP(ip)
	if netIP != nil {
		return ip, nil
	}
	return "", fmt.Errorf("No valid ip found")
}